﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Genuilder.Extensibility
{
	public class GenItem
	{
		ExecutionContext.SourceFile _SourceFile;
		GenEngineStartInfo _StartInfo;
		internal GenItem(ExecutionContext.SourceFile sourceFile, GenEngineStartInfo startInfo, IGenLogger logger)
		{
			File = new FileInfo(sourceFile.Name);
			_StartInfo = startInfo;
			_Name = sourceFile.Name;
			_SourceFile = sourceFile;
			_Extensions = new ExtensionRepository(this);

			if(startInfo.RunHistory != null)
			{
				var historyItem = startInfo.RunHistory.GetGenItemHistoryByName(sourceFile.Name);
				if(historyItem != null)
				{
					_LastModified = historyItem.LastModified;
				}
			}
			_Logger = logger.CreateGenItemLogger(this);
			_GlobalLogger = logger;
		}
		readonly IGenLogger _GlobalLogger;
		private readonly IGenItemLogger _Logger;
		public IGenItemLogger Logger
		{
			get
			{
				return _Logger;
			}
		}

		ExtensionRepository _Extensions;

		public T GetExtension<T>()
		{
			return _Extensions.GetExtension<T>();
		}

		private readonly string _Name;
		public string Name
		{
			get
			{
				return _Name;
			}
		}
		public FileInfo File
		{
			get;
			private set;
		}

		public bool Modified
		{
			get
			{
				File.Refresh();
				if(!File.Exists)
					return true;
				return _LastModified != File.LastWriteTimeUtc;
			}
		}

		public bool Generated
		{
			get
			{
				return _SourceFile.Generated;
			}
		}


		DateTime _LastModified;
		internal GenItem SetLastModified(DateTime lastModified)
		{
			_LastModified = lastModified;
			return this;
		}


		public FileStream Open()
		{
			File.Refresh();
			if(!File.Exists)
				File.Create().Close();
			return new FileStream(File.FullName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
		}

		public void Delete()
		{
			_SourceFile.Parent.RemoveChild(_SourceFile);
		}

		public GenItem CreateChildItem(string childName)
		{
			childName = _StartInfo.CreateGeneratedChildName(childName);
			var childSource = _SourceFile.CreateOrResolve(childName);
			var child = new GenItem(childSource, _StartInfo, _GlobalLogger);
			child.RecreateFile();
			return child;
		}

		internal void RecreateFile()
		{
			if(File.Exists)
				File.Delete();
			File.Create().Close();
			File.Refresh();
		}

		public string ReadAllText()
		{
			using(var fs = Open())
			{
				StreamReader reader = new StreamReader(fs);
				return reader.ReadToEnd();
			}
		}
		public void WriteAllText(string text)
		{
			using(var fs = Open())
			{
				StreamWriter writer = new StreamWriter(fs);
				writer.Write(text);
				writer.Flush();
			}
		}
	}
}
